package com.wangc.commons.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @program:
 * @ClassName:WebFilter
 * @description: web过滤器
 * @author: GYB
 * @create: 2020-04-26 17:09
 **/
@Slf4j
@Component
@WebFilter(urlPatterns = { "/**" }, filterName = "traceIdFilter")
public class TraceIdFilter implements Filter {


    /**
     * 过滤器中处理全局TraceId
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);
        String threadID  = requestWrapper.getHeader("ThreadID");
        if(StringUtils.isBlank(threadID)){
            threadID = java.util.UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        }
        MDC.put("ThreadID", threadID);
        Thread.currentThread().setName(threadID);
        //log.info("header-->{}",getHeadKeyAndValue(req));
        requestWrapper.addHeader("ThreadID",threadID);
        //设置开始时间
        requestWrapper.setAttribute("startTime", System.currentTimeMillis());
        filterChain.doFilter(requestWrapper, servletResponse);
    }

    /**
     * 获取key和value
     * @param httpRequest
     * @return
     */
    private Map<String, String> getHeadKeyAndValue(HttpServletRequest httpRequest) {
        Map<String, String> header = new HashMap<>();
        Enumeration<String> headerNames = httpRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String nextElement = headerNames.nextElement();
            header.put(nextElement, httpRequest.getHeader(nextElement));
        }
        return header;
    }
}
